/* $RCSFile: ADNDynCampaignActivity.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/CRMWrapper3/DynEntities/ADNDynCampaignActivity.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:32  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Data;

using CrmSdk;

namespace AddonNice.CRMWrapper
{
	public class ADNDynCampaignActivity : ADNDynActivity
	{
        protected class Ftor: DFactor
        {
            public Ftor() : base(CrmStr.campaignactivity)
            {}

            public override Type DynType
            { get { return typeof(ADNDynCampaignActivity); } }

            public override string DynTypename
            {   get{ return CrmStr.campaignactivity;}}

            public override DynEntity Build()
            {   return new ADNDynCampaignActivity();}

            public override DynEntity Build(CRMWrapperBase w, InternalDynamicEntity dEntity, PropertyDescriptorCollection wproperties)
            {   return new ADNDynCampaignActivity(w, dEntity, wproperties, null);}

            public override DynEntity Build(CRMWrapperBase w, string PrimaryFieldValue)
            {   return new ADNDynCampaignActivity(w,PrimaryFieldValue);}

            public override DynEntity Build(CRMWrapperBase w,Guid PrimaryKeyValue)
            {   return new ADNDynCampaignActivity(w,PrimaryKeyValue);}
        }

        static ADNDynCampaignActivity(){new Ftor();} 

        /// <summary>
		/// Reserved for template methods: do not use directly
		/// </summary>
        public ADNDynCampaignActivity(): base()
		{}

        public ADNDynCampaignActivity(CRMWrapperBase w,string subj)
			: base(w,subj,CrmStr.campaignactivity)
		{}

        public ADNDynCampaignActivity(CRMWrapperBase w,string subj,string desc,DynEntity partner)
			: base(w, subj,CrmStr.campaignactivity)
		{
            description =   desc;
            if ( partner!= null )
                AddPartner(partner);
		}

        public ADNDynCampaignActivity(CRMWrapperBase w, Guid CrmId)
			: base(w,CrmStr.campaignactivity, CrmId)
		{}

		public ADNDynCampaignActivity(CRMWrapperBase w, InternalDynamicEntity e)
			: base(w,CrmStr.campaignactivity,e,null,null)
		{}

		public ADNDynCampaignActivity(CRMWrapperBase w, InternalDynamicEntity e,PropertyDescriptorCollection prop,InternalColumnSet s)
			: base(w,CrmStr.campaignactivity,e,prop,s)
		{}

        public ADNDynCampaignActivity(ResetWrapperHandler fn,string subj)
			: base(fn,subj,CrmStr.campaignactivity)
		{}

        public ADNDynCampaignActivity(ResetWrapperHandler fn,string subj,string desc,DynEntity partner)
			: base(fn, subj,CrmStr.campaignactivity)
		{
            description =   desc;
            if ( partner!= null )
                AddPartner(partner);
		}

        public ADNDynCampaignActivity(ResetWrapperHandler fn, Guid CrmId)
			: base(fn,CrmStr.campaignactivity, CrmId)
		{}

		public ADNDynCampaignActivity(ResetWrapperHandler fn,InternalDynamicEntity e)
			: base(fn,CrmStr.campaignactivity,e,null,null)
		{}

		public ADNDynCampaignActivity(ResetWrapperHandler fn, InternalDynamicEntity e,PropertyDescriptorCollection prop,InternalColumnSet s)
			: base(fn,CrmStr.campaignactivity,e,prop,s)
		{}
        /*
        bcc Gets or sets the blind carbon copy (BCC) recipients. 
        cc Gets or sets the carbon copy (CC) recipients. 
        from Gets or sets the information about who sent the e-mail. 
        to Gets or sets the recipient party list for the e-mail, and references recipient records such as users and queues. 
        */
        public List<ADNDynActivityParty> PartnersList    =   new List<ADNDynActivityParty>();
        public void AddPartner(DynEntity ent)
        {
            ADNDynActivityParty ap  =   new ADNDynActivityParty(wrapper);
            ap.DefaultPartyName     =   ent.SchemaName;
            ap.partyid              =   ent.PrimaryKeyGuidValue;
            PartnersList.Add(ap);
        }

        [CrmDynAttribute(CrmStr.campaignactivity)]
        public InternalDynamicEntityArray partners 
        {
            get
            {
                return DynamicEntityArrayProperty(CrmStr.partners);
            }
            set
            {
                AddDynamicEntityArrayProperty(CrmStr.partners,value);
            }
        }

        /// <summary>
        /// Owner for this object
        /// </summary>
        [CrmDynAttribute(CrmStr.campaignactivity)]
        public override Guid ownerid
        {
            get
            {
                if ( ContainsKey(CrmStr.ownerid) )
                    return OwnerPropertyValue(CrmStr.ownerid);
                return Guid.Empty;
            }
            set
            {
                AddOwnerProperty(CrmStr.ownerid,CrmStr.systemuser,value);
            }
        }


        /// <summary>
        /// Gets or sets information regarding whether to ignore inactive lists during propagation/execution.
        /// </summary>
        [CrmDynAttribute(CrmStr.campaignactivity)]
        public bool ignoreinactivelistmembers
        {
            get
            {
                return BooleanPropertyValue(CrmStr.ignoreinactivelistmembers);
            }
            set
            {
                AddBooleanProperty(CrmStr.ignoreinactivelistmembers,value);
            }
        }

        /// <summary>
        /// Gets or sets information about whether to send marketing material to list members that prohibit sending of marketing material.
        /// </summary>
        [CrmDynAttribute(CrmStr.campaignactivity)]
        public bool donotsendonoptout
        {
            get
            {
                return BooleanPropertyValue(CrmStr.donotsendonoptout);
            }
            set
            {
                AddBooleanProperty(CrmStr.donotsendonoptout,value);
            }
        }
        
        /// <summary>
        /// Gets or sets whether to ignore the activity if the campaign ran in the last X days. 
        /// </summary>
        [CrmDynAttribute(CrmStr.campaignactivity)]
        public int excludeifcontactedinxdays
        {
            get
            {
                return NumberPropertyValue(CrmStr.excludeifcontactedinxdays);
            }
            set
            {
                AddNumberProperty(CrmStr.excludeifcontactedinxdays,value);
            }
        }

        /// <summary>
        /// Gets or sets the typecode of the activity. 
        /// Research
        /// Content Preparation
        /// Target Marketing List Creation
        /// Lead Qualification
        /// Content Distribution
        /// Direct Initial Contact
        /// Direct Follow-Up Contact
        /// Reminder Distribution
        /// </summary>
        [CrmDynAttribute(CrmStr.campaignactivity)]
        public int typecode 
        {
            get
            {
                return PicklistPropertyIntValue(CrmStr.typecode );
            }
            set
            {
                AddPicklistProperty(CrmStr.typecode ,value);
            }
        }

        public string typecodeLabel
        {
            get
            {
                return PicklistPropertyLabelValue(CrmStr.typecode );
            }
        }
    

        public enum ChannelTypes : int {Phone=1,Appointment,Letter,MailMergeLetter,Fax,MailMergeFax,Email,MailMergeEmail,Other};
        

        /// <summary>
        /// Gets or sets the channeltypecode of the activity. 
        /// Phone
        /// Appointment
        /// Letter
        /// Letter via Mail Merge
        /// Fax
        /// Fax via Mail Merge
        /// E-mail
        /// E-mail via Mail Merge
        /// Other
        /// </summary>
        [CrmDynAttribute(CrmStr.campaignactivity)]
        public int channeltypecode 
        {
            get
            {
                return PicklistPropertyIntValue(CrmStr.channeltypecode );
            }
            set
            {
                AddPicklistProperty(CrmStr.channeltypecode ,value);
            }
        }

        public string channeltypecodeLabel
        {
            get
            {
                return PicklistPropertyLabelValue(CrmStr.channeltypecode );
            }
        }

        /// <summary>
        /// Gets or sets the actualcost, as a monetary amount, for the activity
        /// </summary>
        [CrmDynAttribute(CrmStr.campaignactivity)]
        public decimal actualcost
        {
            get
            {
                return MoneyPropertyValue(CrmStr.actualcost);
            }
            set
            {
                AddMoneyProperty(CrmStr.actualcost,value);
            }
        }

        /// <summary>
        /// Gets the base currency equivalent of the discount specified as a monetary amount for the order.
        /// </summary>
        [CrmDynAttribute(CrmStr.campaignactivity)]
        public decimal actualcost_base
        {
            get
            {
                return MoneyPropertyValue(CrmStr.actualcost_base);
            }
        }
        
        /// <summary>
        /// Gets or sets the budgetedcost, as a monetary amount, for the activity
        /// </summary>
        [CrmDynAttribute(CrmStr.campaignactivity)]
        public decimal budgetedcost
        {
            get
            {
                return MoneyPropertyValue(CrmStr.budgetedcost);
            }
            set
            {
                AddMoneyProperty(CrmStr.budgetedcost,value);
            }
        }

        /// <summary>
        /// Gets the base currency equivalent of the discount specified as a monetary amount for the order.
        /// </summary>
        [CrmDynAttribute(CrmStr.campaignactivity)]
        public decimal budgetedcost_base
        {
            get
            {
                return MoneyPropertyValue(CrmStr.budgetedcost_base);
            }
        }

        protected override Guid internalCreate(bool isAdmin)
        {
            if (PartnersList.Count > 0)
            {
                InternalDynamicEntityArray newArray = wrapper.Util.MakeDynamicArray(PartnersList);
                AddDynamicEntityArrayProperty(CrmStr.partners, newArray);
            }

            return wrapper.CreateFromDynEntity(this,isAdmin);
        }

        #region utilities


        public Guid AddItem(DynEntity dynItem,bool isAdmin)
        {
            return wrapper.Util.AddCampaignActivityItem(this,dynItem,isAdmin);
        }

        public Guid DistributeCampaignActivity(ADNDynActivity dynAct,ADNDynTemplate dynTemp,bool propagate,bool listmemberOwner,bool sendmail,ADNDynSystemUser Owner,bool isAdmin)
        {
            return wrapper.Util.DistributeCampaignActivity(this,dynAct,dynTemp,propagate,listmemberOwner,sendmail,Owner,isAdmin);
        }

       /// <summary>
        /// Build a SortedList 
        /// entName: string.empty for all entities, else the entity
        /// </summary>
        public SortedList<Guid,ADNDynList> ReadAllList(ResetWrapperHandler fn,string entName)
        {
            if (DynCampaignTrace.Sw.TraceVerbose || CRMDynTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNDynCampaignActivity ReadAllList BEG entName: {0}",entName),(DynCampaignTrace.Sw.TraceVerbose)? DynCampaignTrace.Sw.Info:CRMDynTraceSwitch.Sw.Info);
            SortedList<Guid,ADNDynList> Lst                         =   null;
            try
            {
                InternalQueryExpression qe                          =   new InternalQueryExpression();
                qe.EntityName                                       =   CrmStr.list;
                InternalFilterExpression fi                         =   new InternalFilterExpression();
                List<InternalConditionExpression> cLst              =   new List<InternalConditionExpression>();
                if ( !string.IsNullOrEmpty(entName))
                {
                    InternalConditionExpression ex                  =   new InternalConditionExpression();
                    ex.AttributeName                                =   CrmStr.createdfromcode;
                    ex.Operator                                     =   InternalConditionOperator.Equal;
                    switch( entName )
                    {
                        case CrmStr.account:
                        ex.Values                                   =   new object[]{1};
                        break;
                        case CrmStr.contact:
                        ex.Values                                   =   new object[]{2};
                        break;
                        default:
                        case CrmStr.lead:
                        ex.Values                                   =   new object[]{4};
                        break;
                    }
                    cLst.Add(ex);
                }
                if ( cLst.Count > 0 )
                    fi.Conditions                                   =   cLst.ToArray();

                // link from list to campaignactivityitem
                InternalLinkEntity le2                              =   new InternalLinkEntity();
                le2.LinkFromEntityName                              =   CrmStr.list;
                le2.LinkFromAttributeName                           =   CrmStr.listid;
                le2.LinkToEntityName                                =   CrmStr.campaignactivityitem;
                le2.LinkToAttributeName                             =   CrmStr.itemid;
                le2.LinkCriteria                                    =   new InternalFilterExpression();
                le2.LinkCriteria.FilterOperator                     =   InternalLogicalOperator.And;
                InternalConditionExpression ex2                     =   new InternalConditionExpression();
                ex2.AttributeName                                   =   CrmStr.itemobjecttypecode;
                ex2.Operator                                        =   InternalConditionOperator.Equal;
                ex2.Values                                          =   new string[]{CrmStr.list};
                InternalConditionExpression exc                     =   new InternalConditionExpression();
                exc.AttributeName                                   =   CrmStr.campaignactivityid;
                exc.Operator                                        =   InternalConditionOperator.Equal;
                exc.Values                                          =   new string[]{activityid.ToString()};
                le2.LinkCriteria.Conditions                         =   new InternalConditionExpression[]{ex2,exc};

                //add linkentity2 to Query Expression 
                qe.LinkEntities                                     =   new InternalLinkEntity[]{le2};
                ////
                qe.ColumnSet                                        =   new InternalAllColumns();
                qe.Criteria                                         =   fi;
                GenericDynQueryMultiple<ADNDynList> allEntQuery     =   new GenericDynQueryMultiple<ADNDynList>(wrapper,fn,CrmStr.list);
                Lst                                                 =   allEntQuery.retrieveSortedList(qe);
            }
            catch (Exception ex)
            {
                if ( CRMDynTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ADNDynCampaignActivity ReadAllList ex: {0}", ex),CRMDynTraceSwitch.Sw.Info);
                throw;
            }
            if (DynCampaignTrace.Sw.TraceVerbose || CRMDynTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNDynCampaignActivity ReadAllList END Count: {0}",Lst.Count),(DynCampaignTrace.Sw.TraceVerbose)? DynCampaignTrace.Sw.Info:CRMDynTraceSwitch.Sw.Info);
            return Lst;
        }

        /// <summary>
        /// Build a DataTable
        /// entName: string.empty for all entities, else the entity
        /// </summary>
        public DataTable ReadAllListTb(ResetWrapperHandler fn,string entName)
        {
            if (DynCampaignTrace.Sw.TraceVerbose || CRMDynTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNDynCampaignActivity ReadAllListTb BEG entName: {0}",entName),(DynCampaignTrace.Sw.TraceVerbose)? DynCampaignTrace.Sw.Info:CRMDynTraceSwitch.Sw.Info);
            DataTable Tb                                            =   null;
            try
            {
                InternalQueryExpression qe                          =   new InternalQueryExpression();
                qe.EntityName                                       =   CrmStr.list;
                InternalFilterExpression fi                         =   new InternalFilterExpression();
                List<InternalConditionExpression> cLst              =   new List<InternalConditionExpression>();
                if ( !string.IsNullOrEmpty(entName))
                {
                    InternalConditionExpression ex                  =   new InternalConditionExpression();
                    ex.AttributeName                                =   CrmStr.createdfromcode;
                    ex.Operator                                     =   InternalConditionOperator.Equal;
                    switch( entName )
                    {
                        case CrmStr.account:
                        ex.Values                                   =   new object[]{1};
                        break;
                        case CrmStr.contact:
                        ex.Values                                   =   new object[]{2};
                        break;
                        default:
                        case CrmStr.lead:
                        ex.Values                                   =   new object[]{4};
                        break;
                    }
                    cLst.Add(ex);
                }
                if ( cLst.Count > 0 )
                    fi.Conditions                                   =   cLst.ToArray();
                // link from list to campaignactivityitem
                InternalLinkEntity le2                              =   new InternalLinkEntity();
                le2.LinkFromEntityName                              =   CrmStr.list;
                le2.LinkFromAttributeName                           =   CrmStr.listid;
                le2.LinkToEntityName                                =   CrmStr.campaignactivityitem;
                le2.LinkToAttributeName                             =   CrmStr.itemid;
                le2.LinkCriteria                                    =   new InternalFilterExpression();
                le2.LinkCriteria.FilterOperator                     =   InternalLogicalOperator.And;
                InternalConditionExpression ex2                     =   new InternalConditionExpression();
                ex2.AttributeName                                   =   CrmStr.itemobjecttypecode;
                ex2.Operator                                        =   InternalConditionOperator.Equal;
                ex2.Values                                          =   new string[]{CrmStr.list};
                InternalConditionExpression exc                     =   new InternalConditionExpression();
                exc.AttributeName                                   =   CrmStr.campaignactivityid;
                exc.Operator                                        =   InternalConditionOperator.Equal;
                exc.Values                                          =   new string[]{activityid.ToString()};
                le2.LinkCriteria.Conditions                         =   new InternalConditionExpression[]{ex2,exc};

                //add linkentity2 to Query Expression 
                qe.LinkEntities                                     =   new InternalLinkEntity[]{le2};
                ////
                qe.ColumnSet                                        =   new InternalAllColumns();
                qe.Criteria                                         =   fi;
                GenericDynQueryMultiple<ADNDynList> allEntQuery     =   new GenericDynQueryMultiple<ADNDynList>(wrapper,fn,CrmStr.list);
                Tb                                                  =   allEntQuery.retrieveDatatable(qe);
            }
            catch (Exception ex)
            {
                if ( CRMDynTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]ADNDynCampaignActivity ReadAllListTb ex: {0}", ex),CRMDynTraceSwitch.Sw.Info);
                throw;
            }
            if (DynCampaignTrace.Sw.TraceVerbose || CRMDynTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]ADNDynCampaignActivity ReadAllListTb END Count: {0}",(Tb != null) ? Tb.Rows.Count:0),(DynCampaignTrace.Sw.TraceVerbose)? DynCampaignTrace.Sw.Info:CRMDynTraceSwitch.Sw.Info);
            return Tb;
        }
        
        #endregion utilities
    }
}
